package com.foreveross.fetl.core.domain.freight.repository.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.mortbay.log.Log;
import org.springframework.stereotype.Repository;

import com.foreveross.fetl.common.HBaseTable;
import com.foreveross.fetl.common.hbase.client.HBaseHelper;
import com.foreveross.fetl.common.jpa.EntityHibernateRepository;
import com.foreveross.fetl.common.vo.ReturnDoublePlaneInfo;
import com.foreveross.fetl.core.domain.freight.CsairReport;
import com.foreveross.fetl.core.domain.freight.hbase.AgentEntity;
import com.foreveross.fetl.core.domain.freight.repository.ICsairReportRepository;
import com.foreveross.fetl.core.domain.task.SourceEntity;
import com.foreveross.fetl.util.DateUtils;
import com.foreveross.fetl.util.RowkeyUtils;
import com.foreveross.fetl.util.StringUtils;

@Repository("csairReportRepository")
public class CsairReportRepositoryImpl extends EntityHibernateRepository
		implements ICsairReportRepository {
	
	List<String> listCarrierKey =new ArrayList<String>();
	
	@Override
	public List<CsairReport> findByCondition(Date reportDate, Date flightDate,
			int flightType, String fromCity, String toCity, String flightNo,
			String grabHbaseKey) {
		StringBuffer jpql = new StringBuffer(
				"select csair from CsairReport csair where 1=1 ");
		List<Object> conditionVals = new ArrayList<Object>();
		if (reportDate != null) {
			jpql.append(" and csair.reportDate =? ");
			conditionVals.add(reportDate);
		}
		if (flightDate != null) {
			jpql.append(" and csair.flightDate =? ");
			conditionVals.add(flightDate);
		}
		if (flightType == 0 || flightType == 1) {
			jpql.append(" and csair.flightType =? ");
			conditionVals.add(flightType);
		}
		if (null != fromCity && !"".equals(fromCity)) {
			jpql.append(" and csair.fromCity =? ");
			conditionVals.add(fromCity);
		}
		if (null != toCity && !"".equals(toCity)) {
			jpql.append(" and csair.toCity =? ");
			conditionVals.add(toCity);
		}
		if (null != flightNo && !"".equals(flightNo)) {
			jpql.append(" and csair.flightNo =? ");
			conditionVals.add(flightNo);
		}
		if (null != grabHbaseKey && !"".equals(grabHbaseKey)) {
			jpql.append(" and csair.grabHbaseKey =? ");
			conditionVals.add(grabHbaseKey);
		}
		jpql.append(" order by csair.grabTime desc ");
		return super.queryResult(jpql.toString(), conditionVals.toArray());
	}

	@Override
	public void saveOrUpdate(CsairReport csairReport) {
		super.save(csairReport);

	}

	@Override
	public CsairReport findById(Long id) {
		return super.get(CsairReport.class, id);

	}

	@Override
	public int createReport(List<String> airCompanys, List<String> chanels,
			String fromCity, String toCity, Date reportDate, Date flightDate,
			int webType, int flightType) {
		List<CsairReport> listSigle = new ArrayList<CsairReport>();
		listCarrierKey.clear();
		
		Map<String, List<CsairReport>> companyCsairdMap = new HashMap<String, List<CsairReport>>();
		SourceEntity sourceEntity =new SourceEntity();
		
		for (String airCompany : airCompanys) {
			List<SourceEntity> listSource=sourceEntity.findByHbaseKey(airCompany);
			 if(null!=listSource && listSource.size()>0){
				 listCarrierKey.add(listSource.get(0).getCarrierKey());
			 }
			companyCsairdMap.put(airCompany, this.buildChannelAireSpread(
					airCompany, fromCity, toCity, reportDate, flightDate,
					flightType, webType));
			if (webType == 2) {
				this.todayGrabList(airCompany, companyCsairdMap, reportDate,
						flightDate, fromCity, toCity, flightType, webType);
			}
		}

		Map<String, List<CsairReport>> channelCsairMap = new HashMap<String, List<CsairReport>>();
		for (String channel : chanels) {
			channelCsairMap.put(channel, this.buildChannelAireSpread(channel,
					fromCity, toCity, reportDate, flightDate, flightType,
					webType));
		}
		CsairReport csair = null;
		for (String airCompany : airCompanys) {
			List<CsairReport> comCsair = companyCsairdMap.get(airCompany);
			for (CsairReport entity : comCsair) {
				boolean hasChannel = false;
				for (String str : chanels) {
					if (str.startsWith("2")) {
						continue;
					}
					csair = this.getCsairReport(channelCsairMap.get(str),
							entity.getFlightNo());
					if (csair != null) {
						hasChannel = true;
						if (webType == 1) {
							csair.setPrice(entity.getPrice());
							csair.setHbaseKey(entity.getHbaseKey());
							csair.setChannel(entity.getChannel());
							listSigle.add(csair);
						} else {
							entity.setGrabHbaseKey(csair.getGrabHbaseKey());
							entity.setGrabChannel(csair.getChannel());
							if ("00001".equals(str)) {
								entity.setTaobaoPrice(csair.getTaobaoPrice());
								entity.setTaobaoAgentName(csair
										.getTaobaoAgentName());
								entity.setTaobaoAgentAddress(csair
										.getTaobaoAgentAddress());
							}
							if ("00002".equals(str)) {
								entity.setQunarAgentAddress(csair
										.getQunarAgentAddress());
								entity.setQunarAgentName(csair
										.getQunarAgentName());
								entity.setQunarPrice(csair.getQunarPrice());
							}
							if (!this.isCsairReportExit(listSigle,
									entity.getFlightNo())) {
								listSigle.add(entity);
							}
						}
					}
				}
				if (!hasChannel)
					listSigle.add(entity);
			}

			if (1 == webType) {
				for (String str : chanels) {
					if (str.startsWith("2")) {
						continue;
					}
					List<CsairReport> channelAir = channelCsairMap.get(str);
					for (CsairReport cs : channelAir) {
						csair = this.getCsairReport(listSigle,
								cs.getFlightNo(), cs.getGrabHbaseKey());
						if (null == csair) {
							cs.setHbaseKey(airCompany);
							listSigle.add(cs);
						}
					}
				}
			}
		}
		return this.saveList(listSigle);
	}

	@Override
	public int createDouble(List<String> chanels, String fromCity,
			String toCity, Date reportDate, Date flightDate, int webType) {
		return 0;

	}

	/**
	 * 判断list中是否已有存在航班号为flightNo的对象 ,如果存在就返加该对象，不存在返回空对象
	 * 
	 * @param list
	 * @param flightNo
	 * @return
	 */
	public CsairReport getCsairReport(List<CsairReport> list, String flightNo) {
		// CsairReport csairReport =null;
		for (CsairReport csair : list) {
			if (flightNo.equalsIgnoreCase(csair.getFlightNo())) {
				return csair;
			}
		}
		return null;
	}

	/**
	 * 判断list中是否已有存在该航班
	 * 
	 * @param list
	 * @param flightNo
	 * @param channelKey
	 * @return
	 */
	public CsairReport getCsairReport(List<CsairReport> list, String flightNo,
			String channelKey) {

		for (CsairReport csair : list) {
			if (flightNo.equalsIgnoreCase(csair.getFlightNo())
					&& csair.getGrabHbaseKey().equals(channelKey)) {
				return csair;
			}
		}
		return null;
	}

	/**
	 * 获得往返的返程列表
	 * 
	 * @param fcv
	 * @return
	 */
	public List<ReturnDoublePlaneInfo> getReturnDoublePlaneInfoList(
			Map<String, Map<String, String>> curMap) {
		int max = 0;
		Map<String, String> fcv = curMap.get("returnPlaneInfosInfo");
		for (String key : fcv.keySet()) {
			if (key.startsWith("flightId") || key.startsWith("lowerPrice")) {
				String[] strs = key.split("_");
				if (!isNumeric(strs[strs.length - 1])) {
					continue;
				}
				int num = Integer.parseInt(strs[strs.length - 1]);
				if (num > max) {
					max = num;
				}
			}
		}
		boolean isreturnAgentsInfo = false;
		for (String infos : curMap.keySet()) {
			if (infos.equalsIgnoreCase("returnAgentsInfo")) {
				isreturnAgentsInfo = true;
				break;
			}
		}

		List<ReturnDoublePlaneInfo> list = new ArrayList<ReturnDoublePlaneInfo>();
		for (int i = 0; i < max + 1; i++) {
			String flightno = fcv.get("flightId_" + i);
		
			if (curMap.containsKey("returnTransitsInfo")) {
				Map<String, String> transMap = curMap.get("returnTransitsInfo");
				/*
				 * int maxtr=0; for(String key :transMap.keySet()){
				 * if(key.startsWith("flightNo_"+i) ){ String[] strs
				 * =key.split("_"); if(!isNumeric(strs[strs.length-1])){
				 * continue; } int num = Integer.parseInt(strs[strs.length-1]);
				 * if(num > maxtr){ maxtr = num; } } } for (int k = 0; k <
				 * maxtr+1;k++) { if(transMap.get("flightNo_"+i+"_"+k)!=null &&
				 * transMap.get("flightNo_"+i+"_"+k).startsWith("CZ") &&
				 * !transMap
				 * .get("flightNo_"+i+"_"+k).equals(fcv.get("flightId_"+i))){
				 * flightno=flightno+"/"+transMap.get("flightNo_"+i+"_"+k); } }
				 */
				if(transMap.containsKey("flightNo_" + i + "_1"))
					continue;
//				if (transMap.get("flightNo_" + i + "_0") != null) {
//					continue;// 不要中转
//				}
			}
			ReturnDoublePlaneInfo entity = new ReturnDoublePlaneInfo();
			entity.setFlightNo(flightno);
			if (!entity.getFlightNo().startsWith("CZ")) {
				continue;
			}
			entity.setAgentName(fcv.get("agentName_" + i));
			entity.setTotalLowestPrice(Double.parseDouble(fcv.get("lowerPrice_"
					+ i) != null ? fcv.get("lowerPrice_" + i) : "0"));
			if (isreturnAgentsInfo) {// 有代理 取非旗舰代理的最低价
				AgentEntity agentEntity = this.getReturnAgent(
						curMap.get("returnAgentsInfo"), i);
				if (null != agentEntity) {
					entity.setAgentAddress(agentEntity.getAddress());
					entity.setAgentName(agentEntity.getName());
					if (null != agentEntity.getPrice()
							&& agentEntity.getPrice() > 0) {
						entity.setTotalLowestPrice(agentEntity.getPrice());
					}
				}
			}
			if (entity.getTotalLowestPrice() == 0) {
				continue;
			}
			list.add(entity);
		}

		return list;
	}

	/**
	 * 获得返程代理商
	 * 
	 * @param fcv
	 * @param i
	 * @param lowerPrice
	 * @return
	 */
	private AgentEntity getReturnAgent(Map<String, String> fcv, int i) {

		if (null == fcv)
			return null;
		int max = 0;
		for (String key : fcv.keySet()) {
			if (key.startsWith("agentName_" + i)) {
				String[] strs = key.split("_");
				if (!isNumeric(strs[strs.length - 1])) {
					continue;
				}
				int num = Integer.parseInt(strs[strs.length - 1]);
				if (num > max) {
					max = num;
				}
			}
		}
		List<AgentEntity> list = new ArrayList<AgentEntity>();
		for (int j = 0; j < max + 1; j++) {
			AgentEntity entity = new AgentEntity();
			entity.setName(fcv.get("agentName_" + i + "_" + j));
			entity.setAddress(fcv.get("address_" + i + "_" + j));
			entity.setPrice(Double
					.parseDouble(fcv.get("price_" + i + "_" + j) != null ? fcv
							.get("price_" + i + "_" + j) : "0"));
			entity.setType(Integer
					.parseInt(fcv.get("agentType_" + i + "_" + j) != null ? fcv
							.get("agentType_" + i + "_" + j) : "9"));
			list.add(entity);
		}
		AgentEntity agentEntity = null;
		for (AgentEntity en : list) {
			if (null != en.getName() && "中国南方航空".equalsIgnoreCase(en.getName())) {
				en.setType(0);
			}
			if (null == agentEntity) {
				if (en.getPrice() > 0 && 0 != en.getType()) {
					agentEntity = en;
				}
			} else if (en.getPrice() <= agentEntity.getPrice()
					&& en.getPrice() > 0 && 0 != en.getType()) {// 不要旗舰店的
				agentEntity = en;
			}
		}
		return agentEntity;
	}

	/**
	 * 判断是否为数字 是 true
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNumeric(String str) {
		return str.matches("\\d*");
	}

	/**
	 * 保存list到mysql
	 * 
	 * @param list
	 */
	public int saveList(List<CsairReport> list) {
		if (list == null || list.size() <= 0) {
			return 0;
		}
		int i = 0;
		List<CsairReport> oldList = new ArrayList<CsairReport>();
		for (CsairReport en : list) {

			if (en.getWebType() == 2) {// 国际
				oldList = this.findByCondition(en.getReportDate(),
						en.getFlightDate(), en.getFlightType(),
						en.getFromCity(), en.getToCity(), en.getFlightNo(),
						null);
				if (oldList != null && !oldList.isEmpty()) {
					CsairReport oldEntity = oldList.get(0);
					en.setId(oldEntity.getId());// 如果已经存在 则更新
					// 补全数据，会影响实时性
					if (en.getPrice() == null) {
						en.setPrice(oldEntity.getPrice());
					}

					if (en.getTaobaoPrice() == null
							&& null != oldEntity.getTaobaoPrice()) {
						en.setTaobaoPrice(oldEntity.getTaobaoPrice());
						en.setTaobaoAgentAddress(oldEntity
								.getTaobaoAgentAddress());
						en.setTaobaoAgentName(oldEntity.getTaobaoAgentName());
					}
					if (en.getQunarPrice() == null
							&& null != oldEntity.getQunarPrice()) {
						en.setQunarPrice(oldEntity.getQunarPrice());
						en.setQunarAgentAddress(oldEntity
								.getQunarAgentAddress());
						en.setQunarAgentName(oldEntity.getQunarAgentName());
					}
					if (null == en.getGrabHbaseKey()) {
						en.setGrabHbaseKey(oldEntity.getGrabHbaseKey());
						en.setGrabChannel(oldEntity.getGrabChannel());
					}
				}
				if (en.getPrice() != null && en.getPrice() != 0) {
					if (en.getTaobaoPrice() != null && en.getTaobaoPrice() != 0) {
						en.setTaobaoSpreadAmount(en.getPrice()
								- en.getTaobaoPrice());
						en.setTaobaoSpread(round(en.getTaobaoSpreadAmount()
								/ en.getPrice(), 4, BigDecimal.ROUND_HALF_UP));
					}
					if (en.getQunarPrice() != null && en.getQunarPrice() != 0) {
						en.setQunarSpreadAmount(en.getPrice()
								- en.getQunarPrice());
						en.setQunarSpread(round(
								en.getQunarSpreadAmount() / en.getPrice(), 4,
								BigDecimal.ROUND_HALF_UP));
					}

				}
				this.save(en);
				i++;
			} else {// 国内
				i += this.saveDomestic(en);
			}

		}
		return i;
	}

	private int saveDomestic(CsairReport en) {
		int i = 0;
		List<CsairReport> oldList = new ArrayList<CsairReport>();
		oldList = this.findByCondition(en.getReportDate(), en.getFlightDate(),
				en.getFlightType(), en.getFromCity(), en.getToCity(),
				en.getFlightNo(), null);
		if (oldList != null && !oldList.isEmpty()) {
			if (null == en.getGrabHbaseKey()) { // 新数据只有官网的数据
				for (CsairReport oldEntity : oldList) {
					if (en.getPrice() != null) {
						oldEntity.setPrice(en.getPrice());
						oldEntity.setGrabTime(en.getGrabTime());
						oldEntity.setChannel(en.getChannel());
					}
					this.saveNew(oldEntity);
					i++;
				}
			} else if (null == en.getPrice() || en.getPrice() <= 0) {// 新数据没有官网数据
				Boolean isSave = false;
				for (CsairReport oldEntity : oldList) {
					if (null == oldEntity.getGrabHbaseKey()
							|| oldEntity.getGrabHbaseKey().equals(
									en.getGrabHbaseKey())) {
						oldEntity.setGrabTime(en.getGrabTime());
						if(null==oldEntity.getGrabHbaseKey()){
							oldEntity.setGrabHbaseKey(en.getGrabHbaseKey());
							oldEntity.setGrabChannel(en.getGrabChannel());
						}
						if (en.getTaobaoPrice() != null) {
							oldEntity.setTaobaoPrice(en.getTaobaoPrice());
							oldEntity.setTaobaoAgentAddress(en
									.getTaobaoAgentAddress());
							oldEntity.setTaobaoAgentName(en
									.getTaobaoAgentName());
						}
						if (en.getQunarPrice() != null) {
							oldEntity.setQunarPrice(en.getQunarPrice());
							oldEntity.setQunarAgentAddress(en
									.getQunarAgentAddress());
							oldEntity.setQunarAgentName(en.getQunarAgentName());
						}
						this.saveNew(oldEntity);
						i++;
						isSave = true;
					} 
				}
				if(!isSave){
					for (CsairReport oldEntity : oldList) {
						if(null!=oldEntity.getGrabHbaseKey() && !oldEntity.getGrabHbaseKey().equals(en.getGrabHbaseKey()) &&
								null!=oldEntity.getPrice()&&  oldEntity.getPrice()>0){
							if(!isSave){
								en.setPrice(oldEntity.getPrice());
								en.setChannel(oldEntity.getChannel());
								this.saveNew(en);
								i++;
								isSave = true;
							}
						}
					}
				}
				if (!isSave) {
					this.saveNew(en);
					i++;
				}
			} else {
				Boolean isSave = false;
				for (CsairReport oldEntity : oldList) {
					if (null != oldEntity.getGrabHbaseKey()
							&& !oldEntity.getGrabHbaseKey().equals(
									en.getGrabHbaseKey())) {
						oldEntity.setPrice(en.getPrice());
						oldEntity.setGrabTime(en.getGrabTime());
						oldEntity.setChannel(en.getChannel());
						this.saveNew(oldEntity);
						i++;
					} else if (null == oldEntity.getPrice()
							|| oldEntity.getPrice() <= 0) {
						if (!en.getGrabHbaseKey().equals(
								oldEntity.getGrabHbaseKey())) {
							oldEntity.setPrice(en.getPrice());
							oldEntity.setGrabTime(en.getGrabTime());
							oldEntity.setChannel(en.getChannel());
							this.saveNew(oldEntity);
							i++;
						}
					} else {
						oldEntity.setGrabTime(en.getGrabTime());
						oldEntity.setGrabChannel(en.getGrabChannel());
						oldEntity.setGrabHbaseKey(en.getGrabHbaseKey());
						oldEntity.setPrice(en.getPrice());
						if (en.getTaobaoPrice() != null) {
							oldEntity.setTaobaoPrice(en.getTaobaoPrice());
							oldEntity.setTaobaoAgentAddress(en
									.getTaobaoAgentAddress());
							oldEntity.setTaobaoAgentName(en
									.getTaobaoAgentName());
						}
						if (en.getQunarPrice() != null) {
							oldEntity.setQunarPrice(en.getQunarPrice());
							oldEntity.setQunarAgentAddress(en
									.getQunarAgentAddress());
							oldEntity.setQunarAgentName(en.getQunarAgentName());
						}
						this.saveNew(oldEntity);
						i++;
						isSave = true;
					}
				}
				if (!isSave) {
					this.saveNew(en);
					i++;
				}
			}

		} else {
			this.saveNew(en);
			i++;
		}
		return i;
	}

	private void saveNew(CsairReport en) {
		if (en.getPrice() != null && en.getPrice() != 0) {
			if (en.getTaobaoPrice() != null && en.getTaobaoPrice() != 0) {
				en.setTaobaoSpreadAmount(en.getPrice() - en.getTaobaoPrice());
				en.setTaobaoSpread(round(
						en.getTaobaoSpreadAmount() / en.getPrice(), 4,
						BigDecimal.ROUND_HALF_UP));
			}
			if (en.getQunarPrice() != null && en.getQunarPrice() != 0) {
				en.setQunarSpreadAmount(en.getPrice() - en.getQunarPrice());
				en.setQunarSpread(round(
						en.getQunarSpreadAmount() / en.getPrice(), 4,
						BigDecimal.ROUND_HALF_UP));
			}

		}
		this.save(en);
	}

	/**
	 * 对double数据进行取精度.
	 * 
	 * @param value
	 *            double数据.
	 * @param scale
	 *            精度位数(保留的小数位数).
	 * @param roundingMode
	 *            精度取值方式.
	 * @return 精度计算后的数据.
	 */
	public static double round(double value, int scale, int roundingMode) {
		BigDecimal bd = new BigDecimal(value);
		bd = bd.setScale(scale, roundingMode);
		double d = bd.doubleValue();
		bd = null;
		return d;
	}

	private List<CsairReport> buildChannelAireSpread(String channel,
			String fromCity, String toCity, Date reportDate, Date flightDate,
			int flightType, int webType) {
		List<CsairReport> list = new ArrayList<CsairReport>();
		String startRowKey = RowkeyUtils.getRowKey(reportDate, channel,
				fromCity, toCity, flightDate, RowkeyUtils.START_ROW_KEY);
		String endRowKey = RowkeyUtils.getRowKey(reportDate, channel, fromCity,
				toCity, flightDate, RowkeyUtils.STOP_ROW_KEY);
		ResultScanner rs = null;
		try {
			String tableName = HBaseTable.BASE_DATA_FLIGHT;
			if (1 == flightType) {
				tableName = "CRAWL_PLANE_FREIGHT_DOUBLE";
			}
			rs = HBaseHelper.getRecords(tableName, startRowKey, endRowKey);

			for (Result res : rs) {
				List<CsairReport> newList = this.buildCsairReport(res, channel,
						reportDate, flightDate, flightType, webType);
				if (null == newList) {
					continue;
				}
				for (CsairReport c : newList) {
					list.add(c);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			Log.info(StringUtils.getStackTrace(e));
		} finally {
			if (rs != null)
				rs.close();
			rs = null;
		}
		return list;
	}

	public List<CsairReport> buildCsairReport(Result res, String chanel,
			Date reportDate, Date flightDate, int flightType, int webType) {
		List<CsairReport> listCsair = new ArrayList<CsairReport>();

		Map<String, Map<String, String>> curMap = HBaseHelper
				.transformHBaseRowToMap(res);
		Map<String, String> curPalneInfoMap = curMap.get("planeinfo");
		double flightPrice = Float
				.parseFloat(curPalneInfoMap.get("lowerPrice") != null ? curPalneInfoMap
						.get("lowerPrice") : "0");
		if (flightPrice <= 0 && flightType == 0) {
			return null;
		}

		if (curPalneInfoMap.get("flightId") == null)
			return null;

		String flightNo = curPalneInfoMap.get("flightId");
		// if(!flightNo.startsWith("CZ")){
		// return null;
		// }
		String carrierKey=flightNo.substring(0, 2);
		boolean isThekey=false;
		for(String key:listCarrierKey){
			if(carrierKey.equals(key)){
				isThekey=true;
				break;
			}
		}
		if(!isThekey){
			return null;
		}

		String grabChannelName = curPalneInfoMap.get("grabChannel");
		Date grabDate = DateUtils.parse(curPalneInfoMap.get("grabDate")
				.substring(0, 12), "yyyyMMddHHmm");
		Date flightBatchStartTime = DateUtils.parse(
				curPalneInfoMap.get("flightBatchStartTime").substring(0, 8),
				"yyyyMMdd");

		if (curMap.containsKey("transitsInfo")) {
			Map<String, String> transMap = curMap.get("transitsInfo");
			if(transMap.containsKey("flightNo_1"))
				return null;
			
			/*
			 * Map<String ,String> transitsInfo=curMap.get("transitsInfo"); int
			 * max=0; for(String key :transitsInfo.keySet()){
			 * if(key.startsWith("flightNo") || key.startsWith("price")){
			 * String[] strs =key.split("_");
			 * if(!isNumeric(strs[strs.length-1])){ continue; } int num =
			 * Integer.parseInt(strs[strs.length-1]); if(num > max){ max = num;
			 * } } } for (int i = 0; i < max+1; i++) {
			 * if(transitsInfo.get("flightNo_"+i)!=null &&
			 * transitsInfo.get("flightNo_"+i).startsWith("CZ") &&
			 * !transitsInfo.
			 * get("flightNo_"+i).equals(curPalneInfoMap.get("flightId"))){
			 * flightNo=flightNo+"/"+transitsInfo.get("flightNo_"+i); } }
			 */

		}

		if (0 == flightType) {
			Map<String, String> agentMap = new HashMap<String, String>();
			for (String infos : curMap.keySet()) {
				if (infos.equalsIgnoreCase("agentInfos")) {
					agentMap = curMap.get("agentInfos");
					break;
				}
			}
			AgentEntity agent = new AgentEntity();
			agent = this.getAgentEntity(agentMap);
			CsairReport csair = new CsairReport();
			csair.setReportDate(DateUtils.parse(
					DateUtils.format(reportDate, "yyyyMMdd"), "yyyyMMdd"));
			csair.setFlightDate(flightBatchStartTime);
			csair.setFlightNo(flightNo);
			csair.setFlightType(0);
			csair.setFromCity(curPalneInfoMap.get("fromCity"));
			csair.setToCity(curPalneInfoMap.get("toCity"));
			csair.setFromCityName(curPalneInfoMap.get("fromCityName"));
			csair.setToCityName(curPalneInfoMap.get("toCityName"));
			csair.setGrabTime(grabDate);
			csair.setWebType(webType);
			if (chanel.startsWith("2")) {
				csair.setPrice(flightPrice);
				if (webType == 1) {
					csair.setHbaseKey(chanel);
					csair.setChannel(grabChannelName);
				}

			} else {
				if ("00001".equals(chanel)) {

					if (agent != null) {
						csair.setTaobaoAgentName(agent.getName());
						csair.setTaobaoAgentAddress(agent.getAddress());
						if (agent.getPrice() > 0) {
							flightPrice = agent.getPrice();// 有代理就取非旗舰代理的最低价
						}
					}
					csair.setTaobaoPrice(flightPrice);
					if (webType == 1) {
						csair.setGrabHbaseKey(chanel);
						csair.setGrabChannel(grabChannelName);
					}
				}
				if ("00002".equals(chanel)) {
					if (agent != null) {
						csair.setQunarAgentName(agent.getName());
						csair.setQunarAgentAddress(agent.getAddress());
						if (agent.getPrice() > 0) {
							flightPrice = agent.getPrice();// 有代理就取非旗舰代理的最低价
						}
					}

					csair.setQunarPrice(flightPrice);
					if (webType == 1) {
						csair.setGrabHbaseKey(chanel);
						csair.setGrabChannel(grabChannelName);
					}
				}
			}
			listCsair.add(csair);
		} else if (1 == flightType) {

			boolean isReturn = false;
			for (String infos : curMap.keySet()) {
				if (infos.equalsIgnoreCase("returnPlaneInfosInfo")) {
					isReturn = true;
					break;
				}
			}
			if (!isReturn) {
				return null;
			}

			List<ReturnDoublePlaneInfo> doublePlaneInfoEntitys = new ArrayList<ReturnDoublePlaneInfo>();
			doublePlaneInfoEntitys = this.getReturnDoublePlaneInfoList(curMap);
			if (null == doublePlaneInfoEntitys
					|| doublePlaneInfoEntitys.isEmpty()) {
				return null;
			}
			for (ReturnDoublePlaneInfo reEntity : doublePlaneInfoEntitys) {
				if (reEntity.getFlightNo() == null
						|| reEntity.getTotalLowestPrice() == null) {
					continue;
				}
				if (!reEntity.getFlightNo().startsWith("CZ")) {
					continue;
				}

				String flightId = flightNo + "-" + reEntity.getFlightNo();

				CsairReport csairReport = new CsairReport();

				csairReport = new CsairReport();
				csairReport.setReportDate(DateUtils.parse(
						DateUtils.format(reportDate, "yyyyMMdd"), "yyyyMMdd"));
				csairReport.setFlightDate(DateUtils.parse(
						DateUtils.format(flightDate, "yyyyMMdd"), "yyyyMMdd"));
				csairReport.setFlightNo(flightId);
				csairReport.setFlightType(1);
				csairReport.setFromCity(curPalneInfoMap.get("fromCity"));
				csairReport.setToCity(curPalneInfoMap.get("toCity"));
				csairReport
						.setFromCityName(curPalneInfoMap.get("fromCityName"));
				csairReport.setToCityName(curPalneInfoMap.get("toCityName"));
				csairReport.setGrabTime(grabDate);
				csairReport.setWebType(webType);
				listCsair.add(csairReport);

				if (chanel.startsWith("2")) {
					csairReport.setPrice(reEntity.getTotalLowestPrice());
				}
				if ("00001".equals(chanel)) {
					csairReport.setTaobaoPrice(reEntity.getTotalLowestPrice());
					csairReport.setTaobaoAgentName(reEntity.getAgentName());
					csairReport.setTaobaoAgentAddress(reEntity
							.getAgentAddress());

				}
				if ("00002".equals(chanel)) {
					csairReport.setQunarAgentName(reEntity.getAgentName());
					csairReport
							.setQunarAgentAddress(reEntity.getAgentAddress());
					csairReport.setQunarPrice(reEntity.getTotalLowestPrice());
				}

			}

		}
		return listCsair;

	}

	private AgentEntity getAgentEntity(Map<String, String> agentMap) {
		if (null == agentMap || agentMap.isEmpty())
			return null;
		int max = 0;
		for (String key : agentMap.keySet()) {
			if (key.startsWith("name") || key.startsWith("price")) {
				String[] strs = key.split("_");
				if (!isNumeric(strs[strs.length - 1])) {
					continue;
				}
				int num = Integer.parseInt(strs[strs.length - 1]);
				if (num > max) {
					max = num;
				}
			}
		}
		List<AgentEntity> list = new ArrayList<AgentEntity>();
		for (int i = 0; i < max + 1; i++) {
			AgentEntity agentEntity = new AgentEntity();
			agentEntity.setName(agentMap.get("name_" + i));
			double price = Float
					.parseFloat(agentMap.get("price_" + i) != null ? agentMap
							.get("price_" + i) : "0");
			agentEntity.setPrice(price);
			agentEntity.setAddress(agentMap.get("address_" + i));
			agentEntity
					.setType(Integer
							.parseInt(agentMap.get("agentType_" + i) != null ? agentMap
									.get("agentType_" + i) : "9"));
			list.add(agentEntity);
		}
		AgentEntity agentEntity = null;
		for (AgentEntity entity : list) {
			if (null != entity.getName()
					&& "中国南方航空".equalsIgnoreCase(entity.getName())) {
				entity.setType(0);
			}
			if (null == agentEntity) {
				if (entity.getPrice() > 0 && 0 != entity.getType()) {
					agentEntity = entity;
				}
			} else if (agentEntity.getPrice() >= entity.getPrice()
					&& entity.getPrice() > 0 && 0 != entity.getType()) {// 不要旗舰店的
				agentEntity = entity;
			}

		}
		return agentEntity;

	}

	private void todayGrabList(String hbaseKey,
			Map<String, List<CsairReport>> grabMap, Date reportDate,
			Date flightDate, String fromCity, String toCity, int flightType,
			int webType) {
		List<CsairReport> list = new ArrayList<CsairReport>();
		if (null != grabMap && !grabMap.isEmpty()) {
			list = grabMap.get(hbaseKey);
		}
		StringBuffer jpql = new StringBuffer(
				"select csair from CsairReport csair where 1=1 ");
		List<Object> conditionVals = new ArrayList<Object>();
		if (reportDate != null) {
			jpql.append(" and csair.reportDate =? ");
			conditionVals.add(DateUtils.parse(
					DateUtils.format(reportDate, "yyyyMMdd"), "yyyyMMdd"));
		}
		if (flightDate != null) {
			jpql.append(" and csair.flightDate =? ");
			conditionVals.add(DateUtils.parse(
					DateUtils.format(flightDate, "yyyyMMdd"), "yyyyMMdd"));
		}
		if (flightType == 0 || flightType == 1) {
			jpql.append(" and csair.flightType =? ");
			conditionVals.add(flightType);
		}
		if (null != fromCity && !"".equals(fromCity)) {
			jpql.append(" and csair.fromCity =? ");
			conditionVals.add(fromCity);
		}
		if (null != toCity && !"".equals(toCity)) {
			jpql.append(" and csair.toCity =? ");
			conditionVals.add(toCity);
		}

		if (null != hbaseKey && !"".equals(hbaseKey) && 2 != webType) {
			jpql.append(" and csair.hbaseKey =? ");
			conditionVals.add(hbaseKey);
		}
		List<CsairReport> lastList = super.queryResult(jpql.toString(),
				conditionVals.toArray());
		for (CsairReport cs : lastList) {
			if (!this
					.isCsairReportExit(grabMap.get(hbaseKey), cs.getFlightNo())) {
				list.add(cs);
			}
		}
		grabMap.put(hbaseKey, list);
	}

	private boolean isCsairReportExit(List<CsairReport> list, String flightNo) {
		if (null == list) {
			return false;
		}
		for (CsairReport entity : list) {
			if (flightNo.equalsIgnoreCase(entity.getFlightNo())) {
				return true;
			}
		}
		return false;
	}
}
